# -*- coding: utf-8 -*-
"""Order operations module for managing order-related actions."""

import time
from config import GumpIDs, ItemIDs, OrderBooks, NPCs, RuneBooks, Bounds
from uo_items import UOItems
from uo_mobiles import UOMobiles
from uo_player import UOPlayer

class UOOrders:
    """A wrapper class for order-related operations."""
    
    @staticmethod
    def RequestFromNPC(npc: 'Mobile'):
        """Request a bulk order from an NPC.
        
        Args:
            npc: The NPC to request the order from
            
        Returns:
            tuple: (success, message)
                - success: True if order was successfully requested and received
                - message: Description of the result or error message
        """
        # Validate NPC parameter
        if not npc:
            return False, "No NPC provided"

        # Clear journal to ensure clean state for new messages
        Journal.Clear()

        # Step 1: Open context menu and select first option
        Misc.WaitForContext(npc.Serial, 10000)  # Wait up to 10 seconds for context menu
        Misc.ContextReply(npc.Serial, 1)         # Select first option (request order)
        Misc.Pause(1000)                        # Wait for system message

        # Step 2: Check if order is available
        if Journal.Search("An offer may be available in about"):
            return False, "Order not available yet"

        # Step 3: Wait for order request gump
        if not Gumps.WaitForGump(0, 10000):     # Wait up to 10 seconds for gump
            return False, "No gump appeared"

        # Step 4: Handle the order request gump
        current_gump = Gumps.CurrentGump()
        if current_gump == GumpIDs.SMALL_ORDER:
            Gumps.SendAction(current_gump, 1)    # Accept small order
            return True, "Successfully received order"
        elif current_gump == GumpIDs.LARGE_ORDER:
            Gumps.SendAction(current_gump, 1)    # Accept large order
            return True, "Successfully received order"
        else:
            Gumps.SendAction(current_gump, 0)
            return False, f"Unknown gump ID: {current_gump}"
    @staticmethod
    def DeliverOrder(order: 'UOOrder', npc: 'Mobile', timeout: int = 5000):
        """Deliver a completed order to the NPC
        
        Args:
            order: The UOOrder object to deliver
            npc: The NPC Mobile object to deliver to
            timeout: Timeout in milliseconds to wait for delivery confirmation (default: 5000)
            
        Returns:
            tuple: (success, message)
                - success: True if delivery successful, False otherwise
                - message: Description of the result or error message
        """
        # Find NPC
        if not npc:
            return False, "No NPC provided"
            
        # Move closer to NPC
        success, move_message = UOPlayer.MoveToTarget(npc, 1)
        #print(move_message)  # 直接打印移动消息
        if not success:
            return False, move_message  # 直接返回移动失败的消息
            
        # Clear journal at the start
        Journal.Clear()
        
        # Move order to NPC
        Items.Move(order.serial, npc.Serial, 1)
        
        Misc.Pause(1000)

        # Wait for success message with timeout
        start_time = time.time()
        timeout_seconds = timeout / 1000  # Convert milliseconds to seconds
        success_message = "reward"  # Just use the key word
        
        while time.time() - start_time < timeout_seconds:
            # Check for success message
            if Journal.Search(success_message):
                return True, "Successfully delivered order"
                
            Misc.Pause(100)  # Small delay between checks
            
        return False, f"Failed to deliver order - timeout after {timeout}ms waiting for success message"
        
    @staticmethod
    def PutOrderInBook(order_serial: int, book_serial: int) -> bool:
        """Put an order into a book.
        
        Args:
            order_serial: The serial of the order to move
            book_serial: The serial of the book to put the order in
            
        Returns:
            bool: True if successful, False otherwise
        """
        # Move order to book
        Items.Move(order_serial, book_serial, 1)
        
        # Wait for and handle the confirmation gump
        Gumps.WaitForGump(GumpIDs.ORDER_BOOK, 10000)
        Gumps.SendAction(GumpIDs.ORDER_BOOK, 0)
        
        Misc.Pause(800)  # Wait before returning to ensure operation is complete

        return True
        
    @staticmethod
    def TakeOrderFromBook(book_serial):
        """Take an order from a book.
        
        Args:
            book_serial: The serial number of the book to take from
            
        Returns:
            tuple: (success, message)
                - success: True if order was successfully taken
                - message: Description of the result or error message
        """
        # Step 1: Open the book
        Items.UseItem(book_serial)
        
        # Step 2: Wait for and handle the order book gump
        if not Gumps.WaitForGump(GumpIDs.ORDER_BOOK, 10000):
            return False, "Order book gump did not appear"
            
        # Step 3: Select "Get Order" option
        Gumps.SendAction(GumpIDs.ORDER_BOOK, 5)
        
        # Step 4: Wait for and handle the confirmation gump
        if not Gumps.WaitForGump(GumpIDs.ORDER_BOOK, 10000):
            return False, "Confirmation gump did not appear"
            
        # Step 5: Confirm the action
        Gumps.SendAction(GumpIDs.ORDER_BOOK, 0)
        
        # Step 6: Wait for operation to complete
        Misc.Pause(1000)
        
        return True, "Successfully took order from book"
        